﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using System.IO;
using System.Windows.Forms;
using System.Web;

namespace Save2openExcel2007
{
    class libs
    {
        public string esUrl = "http://www.save2open.com/";
        private static string savepath = Path.Combine(System.IO.Path.GetTempPath(), "save2open");
        private static string userfile = Path.Combine(savepath, "everinf.ini");
        private WebClient wc1 = new WebClient();

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="post">以get方式发送的用户名和密码</param>
        /// <returns>成功返回服务器返回的结果，异常返回-1</returns>
        public string upload(string post)
        {

            try
            {
                string File = this.saveTmpdoc();
                if (File.Length != 1)
                {
                    byte[] responseArray = wc1.UploadFile(esUrl + "/upload" + post, "POST", File);
                    return Encoding.ASCII.GetString(responseArray);
                }
                else
                {
                    return File;
                }
            }
            catch
            {
                return "-1";
            }
        }

        /// <summary>
        /// 保存临时文件用于上传，给upload返回临时文档路径
        /// </summary>
        /// <returns>成功返回服务器返回的结果，异常返回-1</returns>
        public string saveTmpdoc()
        {
            //todo save doc
            try
            {
                object missing = System.Reflection.Missing.Value;
                string tmpPath = System.IO.Path.GetTempPath();
                tmpPath = Path.Combine(savepath, "eftmp");
                if (!Directory.Exists(tmpPath))
                {
                    // Create the directory it does not exist.
                    Directory.CreateDirectory(tmpPath);
                }
                var doc = Globals.ThisAddIn.Application.ActiveWorkbook;
                string sPath = doc.Path;
                if (sPath == "")
                {
                    try
                    {
                        doc.Save();                      
                    }
                    catch
                    {
                        return "5";
                    }
                }
                doc = Globals.ThisAddIn.Application.ActiveWorkbook;
                object path = Path.Combine(tmpPath, doc.Name);
                object sourcePath = doc.FullName;
                if ((string)path == (string)sourcePath)
                {
                    string tmpaddpath = Path.Combine(tmpPath, "eftmp");
                    if (!Directory.Exists(tmpaddpath))
                    {
                        // Create the directory it does not exist.
                        Directory.CreateDirectory(tmpaddpath);
                    }


                    path = Path.Combine(tmpaddpath, doc.Name);
                }
                //object missing = System.Reflection.Missing.Value;
                
                doc.Save();
                doc.SaveCopyAs(path);
                return (string)path;
            }
            catch
            {
                return "-1";
            }
        }

        /// <summary>
        /// 保存用户名密码base64编码串到文件
        /// </summary>
        /// <param name="post">以get方式发送的用户名和密码</param>
        /// <returns>成功返回服务器返回的结果，异常返回-1</returns>
        public string savePost(string post)
        {
            try
            {

                if (!Directory.Exists(savepath))
                {
                    // Create the directory it does not exist.
                    Directory.CreateDirectory(savepath);
                }
                StreamWriter postFile = new StreamWriter(userfile);
                postFile.WriteLine(this.EncodeBase64(post));
                postFile.Close();
                return "0";
            }
            catch
            {
                return "-1";
            }
        }

        /// <summary>
        /// 从文件中读取post串并返回
        /// </summary>
        /// <returns>成功返回post串，异常返回-1</returns>
        public string getPost()
        {
            string post = "-1";
            try
            {
                StreamReader postFile = new StreamReader(userfile);
                post = this.DecodeBase64(postFile.ReadLine());
                postFile.Close();
                return post;
            }
            catch
            {
                return post;
            }
        }

        /// <summary>
        /// 删除保存post的文件
        /// </summary>
        public void clearPost()
        {
            if (File.Exists(userfile))
            {
                File.Delete(userfile);
            }
        }

        /// <summary>
        /// 获取用户保存的文件列表
        /// </summary>
        /// <param name="post">以get方式发送的用户名和密码</param>
        /// <returns>成功返回服务器返回的结果，异常返回-1</returns>
        public string getFilelist(string post)
        {
            try
            {
                //todo
                string a = esUrl + "/getfile";
                Stream myStream = wc1.OpenRead(esUrl + "/getfilelist" + post);
                StreamReader sr = new StreamReader(myStream);
                return sr.ReadToEnd();
            }
            catch
            {
                return "-1";
            }
        }

        /// <summary>
        /// 下载文件并打开
        /// </summary>
        /// <param name="post">以get方式发送的用户名和密码</param>
        /// <returns>成功打开文档，返回0，异常返回-1</returns>
        public string getFile(string post, string file)
        {
            try
            {
                //get file download url
                Stream myStream = wc1.OpenRead(esUrl + "/getfile" + post + "&file=" + file);
                StreamReader sr = new StreamReader(myStream);
                string fileurl = sr.ReadToEnd();
                if (fileurl == "-1") return "-1";

                //get tmpfile path
                string[] filetmpname = fileurl.Split('/');
                string filename = filetmpname[filetmpname.Length - 1];
                string tmpPath = System.IO.Path.GetTempPath();
                tmpPath = Path.Combine(savepath, "efopentmp");
                if (!Directory.Exists(tmpPath))
                {
                    // Create the directory it does not exist.
                    Directory.CreateDirectory(tmpPath);
                }
                string tmpfile = Path.Combine(tmpPath, filename);

                object missing = System.Reflection.Missing.Value;

                var thisdoc = Globals.ThisAddIn.Application.Workbooks;
                foreach (Excel.Workbook d in thisdoc)
                {
                    if (d.FullName == tmpfile) d.Close(false, missing, missing);
                }

                //down file to tmpfile
                wc1.DownloadFile(esUrl + fileurl, tmpfile);

                //open tmpfile
                var doc = Globals.ThisAddIn.Application.Workbooks;

                string fileName = @tmpfile;
                object revert = false;
                doc.Open(fileName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
                return "0";

            }
            catch
            {
                return "-1";
            }
        }

        /// <summary>
        /// Base64加密
        /// </summary>
        /// <param name="codeName">加密采用的编码方式</param>
        /// <param name="source">待加密的明文</param>
        /// <returns></returns>
        public string EncodeBase64(Encoding encode, string source)
        {
            string ecode = "";
            byte[] bytes = encode.GetBytes(source);
            try
            {
                ecode = Convert.ToBase64String(bytes);
            }
            catch
            {
                ecode = source;
            }
            return ecode;
        }

        /// <summary>
        /// Base64加密，采用utf8编码方式加密
        /// </summary>
        /// <param name="source">待加密的明文</param>
        /// <returns>加密后的字符串</returns>
        public string EncodeBase64(string source)
        {
            return EncodeBase64(Encoding.UTF8, source);
        }

        /// <summary>
        /// Base64解密
        /// </summary>
        /// <param name="codeName">解密采用的编码方式，注意和加密时采用的方式一致</param>
        /// <param name="result">待解密的密文</param>
        /// <returns>解密后的字符串</returns>
        public string DecodeBase64(Encoding encode, string result)
        {
            string decode = "";
            byte[] bytes = Convert.FromBase64String(result);
            try
            {
                decode = encode.GetString(bytes);
            }
            catch
            {
                decode = result;
            }
            return decode;
        }

        /// <summary>
        /// Base64解密，采用utf8编码方式解密
        /// </summary>
        /// <param name="result">待解密的密文</param>
        /// <returns>解密后的字符串</returns>
        public string DecodeBase64(string result)
        {
            return DecodeBase64(Encoding.UTF8, result);
        }

        /// <summary>
        /// 对中文编码进行解码，从服务器读取到的文件名是编码后的字符串，需要解码
        /// </summary>
        /// <param name="result">待解密的字符串</param>
        /// <returns>解密后的字符串</returns>
        public string ParseString(string input)
        {
            var provider = new Microsoft.CSharp.CSharpCodeProvider();
            var parameters = new System.CodeDom.Compiler.CompilerParameters()
            {
                GenerateExecutable = false,
                GenerateInMemory = true,
            };

            var code = @"
                namespace Tmp
                {
                    public class TmpClass
                    {
                        public static string GetValue()
                        {
                            return """ + input + @""";
                        }
                    }
                }";

            var compileResult = provider.CompileAssemblyFromSource(parameters, code);

            if (compileResult.Errors.HasErrors)
            {
                throw new ArgumentException(compileResult.Errors.Cast<System.CodeDom.Compiler.CompilerError>().First(e => !e.IsWarning).ErrorText);
            }

            var asmb = compileResult.CompiledAssembly;
            var method = asmb.GetType("Tmp.TmpClass").GetMethod("GetValue");

            return method.Invoke(null, null) as string;
        }

        public string errMsg(string code)
        {
            switch (code)
            {
                case "1":
                    return "用户名错误，请重新输入";
                case "2":
                    return "密码错误，请重新输入";
                case "3":
                case "4":
                    return "账户发生异常，请重试或者联系我们";
                case "5":
                    return "未能保存，请先在本地命名保存，再次保存";
                case "6":
                    return "您所使用的空间已经超过上限，无法保存，请联系我们增加空间或者删除不需要的文件";
                default:
                    return "发生错误，请重试或者联系我们";
            }
        }
    }
}
